import {View} from "@tarojs/components";
import {Button, Cell, Empty, Search} from "@antmjs/vantui";
import Utils from "@/utils/common";
import React, {useCallback, useRef, useState} from "react";
import JsonUtils from "@/utils/json_utils";
import {ReportModel} from "@/common/apis/model";
import {orderInfoApi} from "@/common/apis/home_datasource";

definePageConfig({
  navigationBarTitleText: '检测结果搜索'
})

export default function Search_statement() {

  const [items, setItems] = useState<ReportModel[]>()

  const inputKey = useRef('');
  const searchAction = useCallback((e) => {
    if (!Utils.isNotBlank(e.detail)) {
      Utils.showErrorToast('请输入订单号')
      return;
    }
    if (e.detail === inputKey.current) {
      return;
    }
    inputKey.current = e.detail;
    orderInfoApi(inputKey.current).then((res) => {
      if (res && res.reports) {
        const result = JsonUtils.parse<Array<{
          name: string;
          response: {
            data: { name: string; url: string };
          };
        }>>(res!.reports)
        const processedResult = result.map(item => {
          // 取出 name 和 response 里的 data 字段
          const rI: ReportModel = {
            title: item.name,
            name: item.response.data.name,
            url: item.response.data.url
          }
          return rI;
        });
        if (processedResult.length > 0) {
          setItems(processedResult)
        } else {
          Utils.showOkToast('没有查询到数据')
        }
      } else {
        Utils.showOkToast('没有查询到数据')
      }
    })
  }, []);
  return (
    <View style={{display: 'flex', flexDirection: 'column', height: '100vh'}}>
      <View>
        <Search
          placeholder='请输入订单号'
          onSearch={searchAction}
        />
      </View>
      <View style={{flex: 1}}>
        {items && !Utils.isEmpty(items) ? items.map((item, index) => {
          return (
            <View key={index}>
              <Cell title={item.title}>
                <Button type='info' onClick={() => {
                  Utils.scanFile(item.url)
                }}
                >下载</Button>
              </Cell>
            </View>
          )
        }) : <Empty description='暂无数据'/>}
      </View>
    </View>
  )
}






